package hflyeer.gitee.com.controller;

import hflyeer.gitee.com.entity.Employee;
import hflyeer.gitee.com.service.SelfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller("selfController")
public class SelfController {

    @Autowired
    private SelfService selfService;

    @GetMapping("/to_login")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("sn") String sn,@RequestParam("password") String pwd,HttpSession session){
        Employee login = selfService.login(sn,pwd);
        if (login==null){
            return "redirect:to_login";
        }
        session.setAttribute("USER",login);
        return "redirect:/department/list";
    }


    @RequestMapping("/quit")
    public String logout(HttpSession session){
        session.removeAttribute("USER");
        return "redirect:to_login";
    }

    @GetMapping("/to_change_password")
    public String toCheckPwd(){
        return "change_password";
    }

    @PostMapping("/change_password")
    public String checkPwd(HttpSession session,@RequestParam("old") String nowPwd,@RequestParam("new1") String rePwd,@RequestParam("new2") String newPwd){
        Employee user = (Employee) session.getAttribute("USER");
        if(user.getPassword().equals(nowPwd) && rePwd.equals(newPwd)){
            user.setPassword(newPwd);
            selfService.changePassword(user);
            return "self";
        }

        return "redirect:to_change_password";
    }

    @GetMapping("/self")
    public String self(){
        return "self";
    }
}
